const Koa = require('koa');
const KoaStatic = require('koa-static');
const KoaBody = require('koa-body');
const Session = require('koa-session');
const koaJwt = require('koa-jwt')
// var ossRouter = require('app/routers/oss')

let {Port, staticDir, JWT_SECERT} = require('./config');

let app = new Koa();

// 处理异常
const error = require('./app/middleware/error');
app.use(error);

// 解决跨域要在jwt拦截之前
// const cors = require('koa-cors')   // npm i koa-cors
const cors = require('koa2-cors');// CORS是一个W3C标准，全称是"跨域资源共享"
app.use(cors())

//koa-jwt
app.use(koaJwt({secret: JWT_SECERT})
    .unless({
        path: [/\/login/, 'static']
    }
))



// 为静态资源请求重写url
// const rewriteUrl = require('./app/middleware/rewriteUrl');
// app.use(rewriteUrl);
// 使用koa-static处理静态资源
// app.use(KoaStatic(staticDir));


// session
const CONFIG = require('./app/middleware/session');
app.keys = ['session app keys'];
app.use(Session(CONFIG, app));

// 判断是否登录
const isLogin = require('./app/middleware/isLogin');
app.use(isLogin);

// app.use(async (ctx, next) => {
//   ctx.state.user = ctx.session.user;
//   await next();
// });

// 处理请求体数据
const koaBodyConfig = require('./app/middleware/koaBodyConfig');
app.use(KoaBody(koaBodyConfig));



// 使用路由中间件
const Routers = require('./app/routers');
app.use(Routers.routes()).use(Routers.allowedMethods());
// Routers.post('/', ctx => {
//   ctx.set('Access-Control-Allow-Origin', 'http://localhost:5173');
//   ctx.set('Access-Control-Allow-Credentials', 'true');
//   ctx.body = '跨域请求';
// });


const {koaSwagger} = require('koa2-swagger-ui')
const swaggerRouter = require('./app/routers/swagger')

// ......

app.use(swaggerRouter.routes()).use(swaggerRouter.allowedMethods())
const swaggerOption = {
    routePrefix: '/swagger/index.html', // host at /swagger instead of default /docs
    swaggerOptions: {
        url: '/swagger/swagger.json' // example path to json 其实就是之后swagger-jsdoc生成的文档地址
    }
}
app.use(koaSwagger(swaggerOption))


app.listen(Port, () => {
    console.log(`服务器启动在${Port}端口`);
});

// app.use('/api/oss', ossRouter)
